package gdr.connection;

/**
 * Gestisce l'interfaccia web del client, fornendo l'insieme di metodi che consentono l'accesso al server
 * @author Giorgio Vitale
 *
 */
public class ClientManager implements Runnable{
	protected Client client;

	public ClientManager(){
	}
	
	public synchronized void elaboraRichiesta(Object o){
		if (!(o instanceof Message)) return;
		Message m = (Message)o;
		switch (m.getServizio()){
			//case ProtocolloConnessione:
		}
	}
	
	public void run(){
		try{	String u = "U_"+(int)(Math.random()*3);
				boolean b = connect(u);
				System.out.println("connection: "+b+" with username "+u);	
				Thread.sleep(10000);
				disconnect();
				Thread.sleep(6000);
		} catch (Exception e){}
	}

	public void setClient(Client client) {
		this.client = client;
	}
	
	public synchronized boolean connect(String username){
		Message m = new Message(ProtocolloConnessione.REGISTRAZIONE, username);
		try{
			client.sendMessage(m);
			Object o = client.receiveMessage();
			return o instanceof Boolean && ((Boolean)o);
		} catch (Exception e){}
		return false;
	}
	public synchronized boolean disconnect(){
		Message m = new Message(ProtocolloConnessione.DISCONNESSIONE, null);
		try{client.sendMessage(m);
			client.stopClient();
		} catch (Exception e){}
		return false;
	}
	
	
}
